<template>
  <div class="fillWrapper">
    <a-page-header
      style="padding: 12px;background-color: #fff;border-bottom: 1px solid rgb(235, 237, 240)"
      title="申报组织指标详情"
      @back="goToBack()"
    />
    <a-spin :spinning="spinning">
      <a-card :bordered="false" class="topContent">
        <div class="title">{{ detail.targetManagement?.target }}</div>
        <div class="item">说明：{{ detail.targetManagement?.comment }}</div>
        <div class="item">备查资料：{{ detail.targetManagement?.backUpData }}</div>
        <div class="scoreStatus" v-if="role.roleKey === 'EXPERT' || role.roleKey === 'GUIDANCE_EXPERT'">
          <img src="@/assets/images/system/ydf.png" class="statusImg" v-if="detail.isScore === 1"/>
          <img src="@/assets/images/system/wdf.png" class="statusImg" v-if="detail.isScore === 0"/>
        </div>
      </a-card>
      <div class="detailContent">
        <div v-show="!isFullscreen" class="quotaTreeBox">
          <a-input-search
            style="margin: 15px;width: 90%;"
            v-model="filterText"
            allowClear
            placeholder="请输入"
          >
          </a-input-search>
          <div ref="treeBoxRef" class="quotaTreeList">
            <el-tree
              ref="treeRef"
              node-key="id"
              highlight-current
              default-expand-all
              :expand-on-click-node="false"
              :data="treeData"
              :props="elTreeProps"
              :filter-node-method="filterNode"
              @node-click="onSelect"
            >
              <div slot-scope="{ data }" class="fourQuota">
                <!-- <ellipsis :length="16" tooltip>{{ data.target.trim() }}</ellipsis> -->
                <div :class="data.cj == 4 ? '': 'text-gray'" :id="'elTreeId' + data.id">{{ data.target }}</div>
                <template v-if="data.cj == 4">
                  <div class="tip yes" v-if="data.isScore == 1">已打分</div>
                  <div class="tip no" v-else-if="data.isScore == 0">未打分</div>
                </template>
              </div>
            </el-tree>

            <!-- <a-tree
              v-if="treeData.length"
              :tree-data="treeData"
              :replaceFields="{
                children:'childs',
                title:'target',
                key:'id'
              }"
              defaultExpandAll
              :selected-keys="selectedKeys"
              @select="onSelect"
            >
              <template slot="custom" slot-scope="item">
                <div class="fourQuota">
                  <ellipsis :length="16" tooltip>{{ item.target.trim() }}</ellipsis>
                  <div class="tip yes" v-if="item.isScore === 1">已打分</div>
                  <div class="tip no" v-if="item.isScore === 0">未打分</div>
                </div>
              </template>
            </a-tree> -->
            <div class="spinBox" v-if="treeSpinning">
              <a-spin />
            </div>
          </div>
        </div>
        <div class="detail" :style="{height: contentHeight}">
          <div style="z-index: 1000;" class="top">
            <div>
              填报资料：
              <a-button type="primary" @click.stop="webPreview()">网页预览</a-button>
              <span style="margin-left: 10px;color: orange;opacity: 1;">(如加载模糊，可点击‘网页预览’查看源文件)</span>
            </div>
            <div class="full" @click="isFullscreen = !isFullscreen">
              <a-icon :type="isFullscreen ? 'fullscreen-exit' : 'fullscreen'" />
            </div>
          </div>
          <div class="bottom-doc">

            <div v-if="detail.file" class="opt-pdiv">
              <div class="opt-box">
                <div @click="changeScale(1)" class="opt-img"><img src="@/assets/images/up.png" width="22" height="22"/></div>
                <div @click="changeScale(2)" class="opt-img"><img :src="require(`@/assets/images/down${containerScale > 1 ? '-act' : ''}.png`)" width="22" height="22"/></div>
                <div @click="changeScale(3)" class="opt-img"> <img :src="require(`@/assets/images/recover${containerScale > 1 ? '-act' : ''}.png`)" width="18" height="18"/></div>
              </div>
            </div>
            
            <div :style="{transform: 'scale(' + containerScale + ')' , left: containerLeft + 'px', top: containerTop + 'px', cursor: containerScale > 1 ? 'move' : 'pointer' }"
                @mousedown="startDrag"
                @mousemove="doDrag"
                @mouseup="endDrag"
                ref="docBox"
                class="docBox">
              <div @click="wordClick" ref="word"></div>
            </div>
          </div>
          <div class="spinBox" v-if="docSpinning">
            <a-spin />
          </div>
        </div>
        <div class="guidanceBox" :style="{height: contentHeight}">
          <guidance
            ref="guidanceModal"
          />
        </div>
      </div>
    </a-spin>

    <!-- 图片预览 -->
    <div v-if="imgUrl" style="display: none;">
      <el-image 
        ref="imageRef"
        :src="imgUrl" 
        :preview-src-list="[imgUrl]">
      </el-image>
    </div>
  </div>
</template>

<script>
import { Ellipsis } from '@/components'
import bus from '@/utils/bus'
import axios from 'axios'
import { renderAsync } from 'docx-preview'
import { getQuatoDetail, getIsHave, checkUpdateStatus, nextRecord } from '@/api/system'
import { getQuotaTreeByUser } from '@/api/category'
import Guidance from './Guidance'
export default {
  name: 'DeclareSystemFill',
  components: {
    Guidance,
    Ellipsis
  },
  data () {
    return {
      treeId: this.$route.query.treeId,
      targetDeclarationRecordId: this.$route.query.targetDeclarationRecordId, // 指标填报id
      socialOrganizationTypeId: this.$route.query.socialOrganizationTypeId, // 申报体系id
      declarationInfoId: this.$route.query.declarationInfoId, // 申报组织d
      detail: {},
      treeData: [],
      spinning: false,
      docSpinning: false,
      treeSpinning: false,
      target: '',
      docxOptions: {
        breakPages: true, // boolean：在分页符上启用分页
        className: 'docx', // string：默认和文档样式类的类名/前缀
        debug: false, // boolean：启用额外的日志记录
        experimental: true, // boolean：启用实验功能（制表符停止计算）
        ignoreFonts: false, // boolean：禁用字体渲染
        ignoreHeight: false, // boolean：禁止渲染页面高度
        ignoreLastRenderedPageBreak: true, // boolean：在 lastRenderedPageBreak 元素上禁用分页
        ignoreWidth: false, // boolean：禁用页面的渲染宽度
        inWrapper: true, // boolean：启用围绕文档内容的包装器渲染
        renderChanges: false,
        renderEndnotes: true,
        renderFooters: true,
        renderFootnotes: true,
        renderHeaders: true,
        // eslint-disable-next-line no-irregular-whitespace
        trimXmlDeclaration: true, // boolean：如果为true，解析前会从​​ xml 文档中移除 xml 声明
        useBase64URL: false, // boolean：如果为true，图片、字体等会转为base 64 URL，否则使用URL.createObjectURL
        useMathMLPolyfill: false // boolean：包括用于 chrome、edge 等的 MathML polyfill。
      },
      selectedKeys: [],
      isFullscreen: false,
      contentHeight: '100%',
      currentNode: null,
      filterText: '',
      elTreeProps: {
        children: 'childs',
        label: 'target'
      },
      imgUrl: '',
      // 缩放预览参数
      isMouseDown: false,
      containerLeft: 0,
      containerTop: 0,
      containerScale: 1,
      startX: 0,
      startY: 0,
    }
  },
  activated () {
  },
  deactivated () {
  },
  // beforeRouteLeave (to, from, next) {
  //   if (this.$refs.guidanceModal.scoreContent || this.$refs.guidanceModal.annotation) {
  //     scoreRecord({
  //       type: 2,
  //       score: this.$refs.guidanceModal.scoreContent,
  //       annotation: this.$refs.guidanceModal.annotation.trim(),
  //       userId: this.$refs.guidanceModal.userInfo.user.userId,
  //       targetDeclarationRecordId: this.$refs.guidanceModal.targetDeclarationRecordId
  //     }).then(res => {
  //     }).finally(() => {
  //     })
  //   }
  //   next()
  // },
  watch: {
    '$route.query.targetDeclarationRecordId': {
      handler (val) {
        if (val && +val !== +this.targetDeclarationRecordId) {
          this.targetDeclarationRecordId = val
          this.socialOrganizationTypeId = this.$route.query.socialOrganizationTypeId
          this.declarationInfoId = this.$route.query.declarationInfoId
          this.detail = {}
          this.treeData = []
          this.target = ''
          this.spinning = false
          this.docSpinning = false
          this.treeSpinning = false
          if (this.$refs.word) {
            this.$refs.word.innerHTML = ''
          }
          this.getData()
        } else if (val && +val === +this.targetDeclarationRecordId) {
          if (this.$refs.guidanceModal) {
              this.$refs.guidanceModal.guidanceView(this.detail)
            }
        }
      },
      deep: true
    },
    filterText(val) {
      this.$refs.treeRef.filter(val);
    }
  },
  computed: {
    role () {
      return this.$store.getters.roles
      // return { roleKey: 'EXPERT' }
    },
    userInfo () {
      return this.$store.getters.userInfo
    }
  },
  created () {
    this.getData()
  },
  mounted () {
    this.$store.commit('setCollapsed', true)
    // this.contentHeight = document.body.clientHeight - 64 - 12 - 160 - 12 + 'px'
    // window.addEventListener('resize', () => {
    //   this.contentHeight = document.body.clientHeight - 64 - 12 - 160 - 12 + 'px'
    // })
    bus.$on('toRefreshData', (status) => {
      if (status === 'scoreSuccess') {
        // this.getQuotaTreeByUser()
        // this.getDetail(this.detail.id)

        // isScore 不重新加载 tree
        this.setIndexScoreFlag()
        this.nextRecord(this.detail.id)
      }
    })
  },
  methods: {
    // 网页预览
    webPreview() {
      if (!this.detail.file) {
        return
      }
      let fileData = this.detail.file
      let fileUrl = process.env.VUE_APP_OSS_API + fileData.url
      if (!fileData.bucketName) {
        fileUrl = fileData.url.indexOf('pinggu.mkcom.cn') > -1 ? fileData.url : process.env.VUE_APP_FILE_API + fileData.url
      }
      console.log('fileUrl ======> ', fileUrl);
      window.open(`https://view.officeapps.live.com/op/embed.aspx?src=${encodeURIComponent(fileUrl)}`)
    },
    wordClick(event) {
      this.imgUrl = ''
      const target = event.target
      const tagName = target.tagName.toLowerCase()
      console.log('tagName', tagName);
      if ((tagName != 'img' && tagName != 'image') || this.containerScale > 1) {
        return
      }
      if (tagName == 'img') {
        this.imgUrl = target.src
      } else if (tagName == 'image') {
        this.imgUrl = target.href.baseVal
      }
      event.preventDefault()
      this.$nextTick(e => {
        this.$refs.imageRef && (this.$refs.imageRef.showViewer = true)
      })
    },
    // 拖拽预览word
    startDrag(event) {
      this.isMouseDown = true
      this.startX = event.clientX
      this.startY = event.clientY
      event.preventDefault()
    },
    doDrag(event) {
      if (this.isMouseDown && this.containerScale > 1) {
        this.containerLeft += event.clientX - this.startX
        this.containerTop += event.clientY - this.startY;
        this.startX = event.clientX;
        this.startY = event.clientY;
      }
      event.preventDefault()
    },
    endDrag(event) {
      this.isMouseDown = false
      event.preventDefault();
    },
    // 放大、缩小
    changeScale(flag = 1) {
      if (flag == 1) {
        if (this.containerScale < 2.5) {
          this.containerScale += 0.5
        }
      } else if (flag == 2) {
        if (this.containerScale > 1) {
          this.containerScale -= 0.5
        }
      } else {
        this.containerScale = 1
      }
      if (this.containerScale == 1) {
        this.containerLeft = 0
        this.containerTop = 0
      }
    },
    // 设置指标为已读
    setIndexScoreFlag() {
      let treeId = this.detail.targetManagementId
      let findData = null 
      function findTreeData (treeData) {
        for (let index = 0; index < treeData.length; index++) {
          const item = treeData[index];
          if (findData) {
            return
          }
          if (item.id == treeId) {
            findData = item
          }
          if (item.childs) {
            findTreeData(item.childs || [])
          }
        }
      }
      findTreeData(this.treeData)
      findData.isScore = 1
    },
    goToBack() {
      bus.$emit('toRefreshData', 'refreshDetail')
      this.$router.go(-1)
      // 重置参数
      setTimeout(() => {
        this.containerScale = 1
        this.containerLeft = 0
        this.containerTop = 0
        this.isFullscreen = false
      }, 500);
      this.$store.commit('setCollapsed', false)
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.target.indexOf(value) !== -1;
    },
    getData () {
      this.getDetail(this.targetDeclarationRecordId)
      this.getQuotaTreeByUser()
    },
    getDetail (id) {
      if (this.$refs.word) {
        this.$refs.word.innerHTML = ''
      }
      this.spinning = true
      getQuatoDetail({
        id
      })
      .then(res => {
        if (res) {
          this.handleDetail(res)
        }
      }).finally(() => {
          this.spinning = false
        })
    },
    handleDetail (res) {
      this.detail = res
      this.$refs.guidanceModal && this.$refs.guidanceModal.guidanceView(this.detail)
      this.treeId = res.targetManagementId
      this.setTreeCurrenKey(res.targetManagementId)
      let fileData = res.file || {}
      if (fileData.url) {
        // 预览文件
        let docUrl = process.env.VUE_APP_OSS_API + fileData.url
        if (!fileData.bucketName) {
          docUrl = fileData.url.indexOf('pinggu.mkcom.cn') > -1 ? fileData.url : process.env.VUE_APP_FILE_API + fileData.url
        }
        this.getDoc(docUrl)
      } else {
        if (this.$refs.word) {
          this.$refs.word.innerHTML = '<div style="color: #999;text-align: center; opacity: .8;">无预览文件~</div>'
        }
      }
      // if (res.updateStatus === 1) {
      //   this.checkUpdateStatus(res.id)
      // }
    },
    // 选中 tree
    setTreeCurrenKey(treeId) {
      // 左边树同步且高亮
      this.$nextTick(() => {
        let offsetTop = this.$el.querySelector('#elTreeId' + treeId)?.offsetTop || 0
        this.$refs.treeBoxRef && (this.$refs.treeBoxRef.scrollTop = offsetTop - 250)
        this.$refs.treeRef && this.$refs.treeRef.setCurrentKey(treeId)
      })
    },
    checkUpdateStatus (targetDeclarationRecordId) {
      checkUpdateStatus({
        targetDeclarationRecordId
      })
      .then(res => {
        bus.$emit('toRefreshData', 'updateStatus')
      })
    },
    nextRecord (id) {
      if (this.$refs.word) {
        this.$refs.word.innerHTML = ''
      }
      this.spinning = true
      nextRecord({
        id
      })
      .then(res => {
        if (res) {
          this.handleDetail(res)
        } else {
          // 下一条为空，则刷新当前详情
          // this.getDetail(this.detail.id)
          this.$message.warning('后面暂无已填报且未打分的指标~')
        }
      }).finally(() => {
          this.spinning = false
        })
    },
    getQuotaTreeByUser () {
      this.treeSpinning = true
      getQuotaTreeByUser({
        target: this.target,
        declarationInfoId: this.declarationInfoId
      })
      .then(data => {
        // this.treeData = this.getLeaf(res)
        this.treeData = data || []
        this.setTreeCurrenKey(this.treeId)
      }).finally(() => {
        this.treeSpinning = false
      })
    },
    getLeaf (data) {
      for (let i = 0, len = data.length; i < len; i++) {
        if (data[i].cj === 4) {
          data[i].isLeaf = true
          data[i].scopedSlots = {
            title: 'custom'
          }
        } else if (data[i].childs && data[i].childs.length > 0) {
          data[i].disabled = true
          data[i].childs = this.getLeaf(data[i].childs)
        }
      }
      return data
    },
    onSearch () {
      this.getQuotaTreeByUser()
    },
    onSelect (data, treeNode) {
      if (data.cj != 4) {
        this.$refs.treeRef && this.$refs.treeRef.setCurrentKey(this.treeId)
        return
      }
      this.getIsHave(data.id)
    },
    getIsHave (targetManagementId) {
      getIsHave({
        declarationInfoId: this.declarationInfoId,
        targetManagementId
      })
      .then(res => {
        if (res) {
          // 如果填报完成去判断是否可以审核
          // isUserCheck({
          //   recordId: res.id,
          //   userId: this.userInfo.user.userId
          // }).then(check => {
          //   if (check) {
          //     this.getDetail(res.id)
          //     // this.detail = res
          //     // if (res.file && res.file.url) {
          //     //   this.getDoc(res.file.url)
          //     // }
          //   } else {
          //     this.$message.warning('该指标没有审核权限')
          //   }
          // })
          this.getDetail(res.id)
        } else {
          this.$refs.treeRef && this.$refs.treeRef.setCurrentKey(this.treeId)
          this.$message.warning('该指标未填报')
        }
      })
    },
    getDoc (file) {
      this.docSpinning = true
      // file = file.replace('https://pinggu.mkcom.cn/', 'http://localhost:8000/')
      axios
        .get(file, {
          responseType: 'blob' // 注意返回数据类型
        })
        .then((res) => {
          this.containerScale = 1
          this.containerLeft = 0
          this.containerTop = 0
          // 对后端返回二进制流做处理
          const blob = new Blob([res.data])
          // 加载完成后
           renderAsync(blob, this.$refs.word, null, this.docxOptions).then(this.docSpinning = false)
        }).catch(() => {
          this.$refs.word.innerHTML = '<div style="color: red;text-align: center; opacity: .8;">加载文件异常</div>'
          this.docSpinning = false 
        })
    }
  }
}
</script>
<style lang="less">
.quotaTreeBox .el-tree-node__content {
  height: 30px !important;
  padding-right: 5px;
}
.quotaTreeBox .el-tree-node__content:hover {
  background-color: #f0f7ff;
  border-radius: 5px;
}
.quotaTreeBox .el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content{
  background-color: #ccddf2 !important;
  border-radius: 5px;
}
</style>
<style lang="less" scoped>
.fillWrapper {
  // margin: -12px -12px -24px -12px;
  .topContent {
    :deep(.ant-card-body) {
      padding: 5px 100px 5px 12px;
      min-height: 102px;
      .flex-start-vertical()
    }
    .title {
      font-size: 16px;
      font-weight: bold;
      color: rgba(0, 0, 0, 0.85);
    }
    .scoreStatus {
      position: absolute;
      top: 16px;
      right: 16px;
      height: 60px;
      img {
        display: block;
        height: 100%;
      }
    }
  }
  .detailContent {
    width: 100%;
    height: calc( 100vh - 270px);
    margin-top: 15px;
    transition: all 0.2s;
    overflow: hidden;
    position: relative;
    display: flex;
  }
  .quotaTreeBox {
    min-width: 220px;
    width: 300px;
    height: 100%;
    margin-right: 15px;
    background: #fff;
    position: relative;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    .quotaTreeList {
      flex: 1;
      padding: 5px 15px;
      overflow: auto;
      border-top: 1px solid #efefef;
      &::-webkit-scrollbar {
        width: 4px;
      }
      &::-webkit-scrollbar-thumb {
        background: #c1c1c1;
        border-radius: 10px;
        box-shadow: inset 0 0 5px #c1c1c1;
      }
      &::-webkit-scrollbar-track {
        background: transparent;
        border-radius: 0;
        box-shadow: inset 0 0 5px transparent;
      }
    }
    .fourQuota {
      width: 235px;
      cursor: pointer;
      .flex-between();
      .tip {
        width: 50px;
        height: 20px;
        line-height: 20px;
        border-radius: 4px;
        font-size: 12px;
        color: #ffffff;
        text-align: center;
        &.yes {
          background: #21c87f;
        }
        &.no {
          background: #ff5454;
        }
      }
    }
  }
  .detail {
    flex: 1;
    overflow: hidden;
    position: relative;
    background: #fff;
    padding: 50px 16px 0 16px;
    margin-right: 15px;
    .top {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 50px;
      font-size: 14px;
      color: rgba(153, 153, 153, 0.85);
      padding: 0 16px;
      .flex-between();
      .full {
        font-size: 20px;
        color: #1890ff;
        cursor: pointer;
      }
    }
    .bottom-doc {
      width: 100%;
      height: 100%;
      overflow: auto;
      position: relative;
      &::-webkit-scrollbar {
        width: 4px;
      }
      &::-webkit-scrollbar-thumb {
        background: #c1c1c1;
        border-radius: 10px;
        box-shadow: inset 0 0 5px #c1c1c1;
      }
      &::-webkit-scrollbar-track {
        background: transparent;
        border-radius: 0;
        box-shadow: inset 0 0 5px transparent;
      }
    }
    .docBox {
      width: 100%;
      cursor: pointer;
      position: relative;
      transform-origin: top left; 
    }
    .opt-pdiv {
      position: sticky;
      left: 20px;
      top: 20px;
      z-index: 100;
    }
    .opt-box {
      position: absolute;
      left: 10px;
      top: 10px;
      background-color: #fff;
      border-radius: 2px;
      border: 1px solid #eee;
      border-bottom: none;
      .opt-img {
        padding: 5px;
        border-bottom: 1px solid #eee;
        text-align: center;
        cursor: pointer;
      }
    }
  }
  .guidanceBox {
    min-width: 220px;
    width: 300px;
    transition: all 0.2s;
    overflow: hidden;
    background: #fff;
  }
  .spinBox {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    .flex-center();
  }
  :deep(.ant-tree) {
    li .ant-tree-node-content-wrapper.ant-tree-node-selected {
      background: none;
      color: #0084fe;
    }
  }
}
</style>
